package com.simon.hse.activity.danger;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.simon.hse.MyApplication;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.CommonInput;
import com.simon.hse.http.entity.DangerRectifyOutput;
import com.simon.hse.http.entity.DropDownOutput;
import com.simon.hse.interfaces.PopListener;
import com.simon.hse.utils.DateTimeUtils;
import com.simon.hse.utils.PopupWindowUtils;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import retrofit2.Call;

/**
 * 隐患整改计划
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_danger_rectify)
public class DangerRectifyActivity extends BaseActivity implements PopListener {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.ll_function_area)
    LinearLayout mLl_function_area;

    @ViewInject(R.id.tv_function_area)
    TextView mTv_function_area;

    @ViewInject(R.id.ll_function_state)
    LinearLayout mLl_function_state;

    @ViewInject(R.id.tv_function_state)
    TextView mTv_function_state;

    @ViewInject(R.id.ll_more)
    LinearLayout mLl_more;

    @ViewInject(R.id.ll_rectify_more_level)
    LinearLayout mLl_rectify_more_level;

    @ViewInject(R.id.tv_rectify_more_level)
    TextView mTv_rectify_more_level;

    @ViewInject(R.id.ll_rectify_more_category)
    LinearLayout mLl_rectify_more_category;

    @ViewInject(R.id.tv_rectify_more_category)
    TextView mTv_rectify_more_category;

    @ViewInject(R.id.ll_rectify_more_classify)
    LinearLayout mLl_rectify_more_classify;

    @ViewInject(R.id.tv_rectify_more_classify)
    TextView mTv_rectify_more_classify;

    @ViewInject(R.id.ll_rectify_more_before_date)
    LinearLayout mLl_rectify_more_before_date;

    @ViewInject(R.id.tv_rectify_more_before_date)
    TextView mTv_rectify_more_before_date;

    @ViewInject(R.id.ll_rectify_more_after_date)
    LinearLayout mLl_rectify_more_after_date;

    @ViewInject(R.id.tv_rectify_more_after_date)
    TextView mTv_rectify_more_after_date;

    @ViewInject(R.id.smartrefresh)
    SmartRefreshLayout mSmartRefresh;

    @ViewInject(R.id.recyclerview)
    RecyclerView mRecyclerView;

    private int currentPage = 1, totalPage = 1;
    private CommonEmptyAdapter mCommonEmptyAdapter;
    private List<DangerRectifyOutput.DataBean.PageDataBean> mDataBeanList = new ArrayList<>();
    private List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mDangerAreasList = new ArrayList<>();// 区域
    private List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mDangerStateList = new ArrayList<>();// 整改状态
    private List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mDangerClassifyList = new ArrayList<>();// 隐患分类
    private List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mDangerLevelList = new ArrayList<>();// 隐患等级

    private boolean isShowMore = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTv_common_title.setText("隐患整改计划");

        initRecyclerView();
        initSelectFunctions();
        initData();
    }

    @Event(value = {R.id.iv_common_left, R.id.ll_function_area, R.id.ll_function_state, R.id.ll_function_more})
    private void clickButton(View view) {
        switch (view.getId()) {
            case R.id.iv_common_left:
                finish();
                break;
            case R.id.ll_function_area:
                initCommonPop(mLl_function_area, mTv_function_area, mDangerAreasList);
                break;
            case R.id.ll_function_state:
                initCommonPop(mLl_function_state, mTv_function_state, mDangerStateList);
                break;
            case R.id.ll_function_more:
                if (isShowMore) {
                    mLl_more.setVisibility(View.GONE);
                } else {
                    mLl_more.setVisibility(View.VISIBLE);
                }
                isShowMore = !isShowMore;
                break;
        }
    }

    @Event(value = {R.id.ll_rectify_more_level, R.id.ll_rectify_more_category, R.id.ll_rectify_more_classify, R.id.ll_rectify_more_before_date, R.id.ll_rectify_more_after_date, R.id.tv_more_confirm, R.id.tv_more_reset})
    private void more(View view) {
        switch (view.getId()) {
            case R.id.ll_rectify_more_level:
                initCommonPop(mLl_rectify_more_level, mTv_rectify_more_level, mDangerLevelList);
                break;
            case R.id.ll_rectify_more_category:
                initCommonPop(mLl_rectify_more_category, mTv_rectify_more_category, mDangerClassifyList);
                break;
            case R.id.ll_rectify_more_classify:
                initCommonPop(mLl_rectify_more_classify, mTv_rectify_more_classify, mDangerClassifyList);
                break;
            case R.id.ll_rectify_more_before_date:
                reportBeforeDate();
                break;
            case R.id.ll_rectify_more_after_date:
                reportAfterDate();
                break;
            case R.id.tv_more_confirm:
                mLl_more.setVisibility(View.GONE);
                isShowMore = !isShowMore;
                break;
            case R.id.tv_more_reset:
                mTv_rectify_more_level.setText("");
                mTv_rectify_more_level.setHint("请选择");
                mTv_rectify_more_category.setText("");
                mTv_rectify_more_category.setHint("请选择");
                mTv_rectify_more_classify.setText("");
                mTv_rectify_more_classify.setHint("请选择");
                break;
        }
    }

    private void initRecyclerView() {
        mSmartRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (currentPage * 10 < totalPage) {
                    currentPage++;
                    initData();
                } else {
                    mSmartRefresh.finishLoadMoreWithNoMoreData();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                mDataBeanList.clear();
                initData();
            }
        });

        LinearLayoutManager llm = new LinearLayoutManager(DangerRectifyActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        mCommonEmptyAdapter = new CommonEmptyAdapter(DangerRectifyActivity.this, R.layout.layout_item_danger_rectify, mDataBeanList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<DangerRectifyOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, DangerRectifyOutput.DataBean.PageDataBean dataBean) {
                TextView tv_danger_rectify_title = holder.getView(R.id.tv_danger_rectify_title);
                TextView tv_danger_rectify_state = holder.getView(R.id.tv_danger_rectify_state);
                TextView tv_danger_rectify_person = holder.getView(R.id.tv_danger_rectify_person);

                tv_danger_rectify_title.setText(dataBean.getRiskDescription());
                tv_danger_rectify_title.setText(dataBean.getStateText());
                switch (dataBean.getState()) {// (/0待审批/1已生效/2审批退回/3验收通过/4验收退回)
                    case "0":
//                        tv_danger_rectify_state.setText("待审批");
                        tv_danger_rectify_state.setBackgroundResource(R.drawable.rect_yellow_corner_5);
                        break;
                    case "1":
//                        tv_danger_rectify_state.setText("已生效");
                        tv_danger_rectify_state.setBackgroundResource(R.drawable.rect_blue_corner_5);
                        break;
                    case "2":
//                        tv_danger_rectify_state.setText("审批退回");
                        break;
                    case "3":
//                        tv_danger_rectify_state.setText("验收通过");
                        tv_danger_rectify_state.setBackgroundResource(R.drawable.rect_blue_corner_5);
                        break;
                    case "4":
//                        tv_danger_rectify_state.setText("验收退回");
                        break;
                }
                tv_danger_rectify_person.setText("负责人：" + dataBean.getDiscovererText());
            }
        });

        mCommonEmptyAdapter.setOnItemEmptyClickListener(new CommonEmptyAdapter.OnItemEmptyClickListener() {
            @Override
            public void setOnEmptyClickListener() {
                initData();
            }

            @Override
            public void setOnItemClickListener(View view, int position) {
                if (!isShowMore) {
                    Intent intent = new Intent(DangerRectifyActivity.this, DangerRectifyDetailActivity.class);
                    DangerRectifyOutput.DataBean.PageDataBean pageDataBean = mDataBeanList.get(position);
                    Bundle bundle = new Bundle();
                    bundle.putString("ID", pageDataBean.getId());
                    bundle.putString("STATUS", pageDataBean.getState());
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mCommonEmptyAdapter.setHasStableIds(true);
        mRecyclerView.setAdapter(mCommonEmptyAdapter);
    }

    private void initData() {
        CommonInput commonInput = new CommonInput();
        CommonInput.ModelBean modelBean = new CommonInput.ModelBean();
        commonInput.setModel(modelBean);
        commonInput.setLimit(10);
        commonInput.setOffset(10 * (currentPage - 1));

        Call<String> call = HttpManager.getInstance().requestService().DANGER_RECTIFY_LIST(HttpManager.getInstance().requestBody(commonInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                DangerRectifyOutput dangerRectifyOutput = new Gson().fromJson(result, DangerRectifyOutput.class);
                if (dangerRectifyOutput.getResult().equals("Success")) {
                    totalPage = dangerRectifyOutput.getData().getRowCount();
                    List<DangerRectifyOutput.DataBean.PageDataBean> dataBeanList = dangerRectifyOutput.getData().getPageData();
                    mDataBeanList.addAll(dataBeanList);
                    mCommonEmptyAdapter.notifyDataSetChanged();

                    mSmartRefresh.finishRefresh();
                    mSmartRefresh.finishLoadMore();
                } else {
                    ToastUtils.getInstance().showShortToastBottom(dangerRectifyOutput.getMessage().toString());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 初始化搜索条件
     */
    private void initSelectFunctions() {
        DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean = new DropDownOutput.DataBean.DataDicListBean.ValueBean();
        valueBean.setValue("全部");
        valueBean.setKey("");

        mDangerAreasList.add(valueBean);
        mDangerAreasList.addAll(MyApplication.getInstance().mDangerAreasList);

        mDangerStateList.add(valueBean);
        mDangerStateList.addAll(MyApplication.getInstance().mDangerStateList);

        mDangerClassifyList.add(valueBean);
        mDangerClassifyList.addAll(MyApplication.getInstance().mDangerClassifyList);

        mDangerLevelList.add(valueBean);
        mDangerLevelList.addAll(MyApplication.getInstance().mDangerLevelList);
    }

    /**
     * 排查情况Pop
     */
    private void initCommonPop(LinearLayout mLl, final TextView mTv, final List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mList) {
        View inflate = LayoutInflater.from(DangerRectifyActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(DangerRectifyActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(DangerRectifyActivity.this, R.layout.layout_item_common_more_department, mList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<DropDownOutput.DataBean.DataDicListBean.ValueBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, DropDownOutput.DataBean.DataDicListBean.ValueBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getValue());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean = mList.get(position);
                mTv.setText(valueBean.getValue());
                PopupWindowUtils.getInstance().closePop();
                upData();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(DangerRectifyActivity.this, inflate, mLl);
    }

    /**
     * 上报日期-前
     */
    private void reportBeforeDate() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        startDate.set(1949, 1, 1);
        String currentYMD = DateTimeUtils.getCurrentYMD();
        String[] split = currentYMD.split("-");
        selectedDate.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));
        endDate.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));

        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(DangerRectifyActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat sdf_ymd = new SimpleDateFormat("yyyy-MM-dd");
                mTv_rectify_more_before_date.setText(sdf_ymd.format(date));
                upData();
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .build();

        pvTime.show();
    }

    /**
     * 上报日期-后
     */
    private void reportAfterDate() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        startDate.set(1949, 1, 1);
        String currentYMD = DateTimeUtils.getCurrentYMD();
        String[] split = currentYMD.split("-");
        selectedDate.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));
        endDate.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));

        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(DangerRectifyActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat sdf_ymd = new SimpleDateFormat("yyyy-MM-dd");
                mTv_rectify_more_after_date.setText(sdf_ymd.format(date));
                upData();
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .build();

        pvTime.show();
    }
    @Override
    public void upData() {
        currentPage = 1;
        mDataBeanList.clear();
        initData();
    }
}
